<?php

namespace app\controller;

use app\BaseController;
use app\exception\AuthException;
use app\exception\TokenException;

class Base extends BaseController
{
    protected $user;

    public function initialize()
    {
        header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With");
        header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS");
        header("access-control-allow-credentials: true");
        header("access-control-allow-origin: *");

        $res = getUserSimpleInfo(getHeaderToken());
        if ($res['code'] != 0) {
            throw new TokenException('登录过期，请重新登录', 413);
        }

        $this->user = $res['data'];
        $skipAuth = config('auth.skip_auth');

        // 权限鉴定
        $authMap = cache('user_auth_' . $this->user['id']);
        if ($authMap != '*') {

            $controller = strtolower(request()->controller());
            $action = strtolower(request()->action());

            $checkAuth = $controller . '/' . $action;

            if (!isset($authMap[$checkAuth]) && !isset($skipAuth[$checkAuth])) {
                throw new AuthException('无权限', 403);
            }
        }
    }
}